﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI;

using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.ExceptionManagement;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using ProjectFileUrls = Kiiro.Common.Utility.Constants.ProjectFileUrls;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class MyWork : BasePage
    {
        public Pager V2Pager
        {
            get { return (Pager)v2Pager; }
        }

        public WelcomeMessagePanel V2WelcomeMessagePanel
        {
            get { return (WelcomeMessagePanel)v2WelcomeMessagePanel; }
        }

        public Filter Filter
        {
            get { return (Filter)v2Filter; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        private List<Work> work = new List<Work>();
        private List<Work> Work
        {
            get { return work; }
            set { work = value; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            try
            {
                AddCommandButtons ( );
                V2WelcomeMessagePanel.MyWorkPage = true;
                litTitle.Text = "My Work";
                if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
                {
                    litTitle.Text = KiiroMaster.V2Header.Project.Title + " - My Work";
                }

                V2Pager.NextClick += new EventHandler(RePopulatePage);
                V2Pager.PrevClick += new EventHandler(RePopulatePage);
                V2Pager.EntitiesPerPageChange += new EventHandler(RePopulatePage);

                Work = WorkModel.GetMyWork(SiteCollectionId, ServerRelativeUrl, CurrentUser);
                Work.ForEach(x => x.CustomFieldNamesAndValues = CustomModel.HarvestCustomFields(typeof(Work), x.Id, HttpContext.Current, x.SiteCollectionId, x.ServerRelativeUrl));

                Filter.EntityType = EntityType.Work;
                Filter.Entities = Work.Cast<BaseEntity> ( ).ToList ( );
                Work = Filter.Apply ( ).Cast<Work> ( ).ToList ( );

                PopulatePage();
            }
            catch ( Exception ex )
            {
                ExceptionManager.HandleException ( ex, true );
            }
        }

        #region Page Related Methods

        private void PopulatePage()
        {
            if ( Work.Count > 0 || !string.IsNullOrEmpty ( Request.Params [ "Field" ] ) )
            {
                if (V2Pager.SortExpression != "DueDate")
                {
                    List<Work> sortedWorkList = new List<Work>();
                    //sort the work List by End Date desc, and title asc
                    var workNotCompleted =
                            from workItem in Work
                            orderby workItem.EndDate ascending, workItem.Title ascending
                            where workItem.Status != StatusType.Completed && workItem.Status != StatusType.Closed && workItem.EndDate != default(DateTime) && workItem.EndDate != null
                            group workItem by new { workItem.EndDate.Date, workItem.Status } into g
                            select new { EndDate = g.Key, Status = g.Key, sortedWorkItem = g };

                    #region Work Group With End Date and Not Completed
                    foreach (var workGroup in workNotCompleted)
                    {
                        foreach (var workDetail in workGroup.sortedWorkItem)
                        {
                            Work workToBeAdded = new Work();
                            workToBeAdded = workDetail;
                            sortedWorkList.Add(workToBeAdded);
                        }
                    }
                    #endregion

                    //sort the work List by Title for not completed, not closed , adn no due date
                    var workNotCompletedNoDueDate =
                            from workItem in Work
                            orderby workItem.EndDate ascending, workItem.PercentageComplete ascending, workItem.Title ascending
                            where workItem.Status != StatusType.Completed && workItem.Status != StatusType.Closed && (workItem.EndDate == default(DateTime) || workItem.EndDate == null)
                            group workItem by new { workItem.EndDate.Date, workItem.Status } into g
                            select new { EndDate = g.Key, Status = g.Key, sortedWorkItem = g };

                    #region Work Group With No End Date and  both not Completed and not Closed
                    foreach (var workGroup in workNotCompletedNoDueDate)
                    {
                        foreach (var workDetail in workGroup.sortedWorkItem)
                        {
                            Work workToBeAdded = new Work();
                            workToBeAdded = workDetail;
                            sortedWorkList.Add(workToBeAdded);
                        }
                    }
                    #endregion


                    //sort the work List by Title for completed, not completed
                    var workCompleted =
                            from workItem in Work
                            orderby workItem.EndDate ascending, workItem.PercentageComplete ascending, workItem.Title ascending
                            where (workItem.Status == StatusType.Completed || workItem.Status == StatusType.Closed)
                            group workItem by new { workItem.EndDate.Date, workItem.Status } into g
                            select new { EndDate = g.Key, Status = g.Key, sortedWorkItem = g };

                    #region Work Group With No End Date and  both Completed and not Completed
                    foreach (var workGroup in workCompleted)
                    {
                        foreach (var workDetail in workGroup.sortedWorkItem)
                        {
                            Work workToBeAdded = new Work();
                            workToBeAdded = workDetail;
                            sortedWorkList.Add(workToBeAdded);
                        }
                    }
                    #endregion

                    V2Pager.PopulatePager(sortedWorkList.Count, Constants.PagerEntity.Work);

                    rptWork.DataSource = sortedWorkList.GetRange(V2Pager.PagingIndex, V2Pager.DisplayedCount);
                    rptWork.DataBind();
                }
                else
                {
                    SortList();

                    V2Pager.PopulatePager(Work.Count, Constants.PagerEntity.Work);

                    rptWork.DataSource = work.GetRange(V2Pager.PagingIndex, V2Pager.DisplayedCount);
                    rptWork.DataBind();
                }
            }
            else
            {
                pnlPanel.Visible = false;
                v2Pager.Visible = false;
                v2WelcomeMessagePanel.Visible = true;
                V2WelcomeMessagePanel.ShowPanel = true;
                V2WelcomeMessagePanel.ServerRelativeUrl = ServerRelativeUrl;
                V2WelcomeMessagePanel.ShowHidePanel(Constants.PagerEntity.Work, PermissionBitsWork);
                actionBar.Visible = false;
            }
        }

        private void AddCommandButtons()
        {
            if (PermissionBitsWork[0])
            {
                LinkButton btnCreateIssue = new LinkButton();
                btnCreateIssue.Text = "Create a New Issue";
                btnCreateIssue.Attributes.Add("class", "icon-add");
                btnCreateIssue.Click += new EventHandler(btnCreateIssue_Click);
                NavigationSub.Commands.Add(btnCreateIssue);

                LinkButton btnCreateTask = new LinkButton();
                btnCreateTask.Text = "Create a New Task";
                btnCreateTask.Attributes.Add("class", "icon-add");
                btnCreateTask.Click += new EventHandler(btnCreateTask_Click);
                NavigationSub.Commands.Add(btnCreateTask);
            }
        }

        protected void btnCreateTask_Click(object sender, EventArgs e)
        {
            Response.Redirect(ServerRelativeUrl + ProjectFileUrls.TaskNew);
        }

        protected void btnCreateIssue_Click(object sender, EventArgs e)
        {
            Response.Redirect(ServerRelativeUrl + ProjectFileUrls.IssueNew);
        }

        protected void rptWork_ItemDataBound(object source, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                Literal litNumItems = (Literal)rptWork.FindControl("litNumItems");
                if (litNumItems != null)
                {
                    litNumItems.Text = ((List<Work>)rptWork.DataSource).Count.ToString();
                }
            }
            else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                Work work = (Work)e.Item.DataItem;
                MyWorkItem v2WorkItem = (MyWorkItem)e.Item.FindControl("v2WorkItem");

                v2WorkItem.IsLastItem = e.Item.ItemIndex == V2Pager.DisplayedCount - 1;
                v2WorkItem.Work = work;
            }
        }

        #endregion

        #region Pager Related Methods

        private void SortList()
        {
            dueSort.Visible = false;

            Literal sortText = dueSort;
            string sortTextTemplate = "<img src='/_layouts/images/Kiiro/icon-sort-{0}.gif' />";

            switch (V2Pager.SortExpression)
            {
                case "DueDate":
                    sortText = dueSort;
                    work.Sort(delegate(Work w1, Work w2) { return w1.EndDate.CompareTo(w2.EndDate); });
                    break;
                default:
                    break;
            }

            sortText.Visible = true;

            if (V2Pager.SortDirection == SortDirection.Ascending)
            {
                sortText.Text = string.Format(sortTextTemplate, "asc");
            }
            else
            {
                sortText.Text = string.Format(sortTextTemplate, "desc");
                work.Reverse();
            }
        }

        private void RePopulatePage(object sender, EventArgs e)
        {
            PopulatePage();
        }

        protected void SortBy_Click(object sender, EventArgs e)
        {
            LinkButton link = (LinkButton)sender;
            if (V2Pager.SortDirection == SortDirection.Ascending && V2Pager.SortExpression == link.CommandArgument)
                V2Pager.SortDirection = SortDirection.Descending;
            else
                V2Pager.SortDirection = SortDirection.Ascending;
            V2Pager.SortExpression = link.CommandArgument;

            V2Pager.IsSortClick = true;
            V2Pager.DisplayedCount = rptWork.Items.Count;
            PopulatePage();
        }

        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Work/MyWork.aspx.cs $
 * 
 * 21    2/08/10 2:28p Camerons
 * 
 * 20    2/08/10 12:00p Camerons
 * 
 * 19    1/06/10 12:39p Camerons
 * 
 * 18    12/07/09 3:16p Stefanf
 * 
 * 17    12/02/09 12:30p Stefanf
 * 
 * 16    9/11/09 11:02a Camerons
 * 
 * 15    6/11/09 12:44p Camerons
 * 
 * 14    7/10/09 3:54p Shafia
 * 
 * 13    7/10/09 3:42p Shafia
 * FIXED!   
 * Page load was calling GetAllwork method instead of GetMyWork
 * 
 * 12    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 11    25/09/09 10:44a Shafia
 * fixed sort method to retain page index and display correct number of
 * rows when sort is clicked.
 * 
 * 10    23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 9     21/09/09 12:42p Shafia
 * 
 * 8     18/09/09 2:33p Shafia
 * New Pager Implemented. All data binding is done on the page itself not
 * on the Pager control
 * 
 * 7     8/09/09 10:48a Camerons
 * Added check for Request.UrlReferrer to hopefully fix the
 * ThreadAbortException being reported in the log files
 * 
 * 6     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/